package utils

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

// StructCopy 结构体复制
// source 当前有值的结构体
// target 接受值的结构体指针
// fields 需要的设置的属性
func StructCopy(source any, target any, fields ...string) (err error) {
	svv := reflect.ValueOf(source)
	tvv := reflect.ValueOf(target)

	// 检查 target 是否是结构体指针
	if svv.Kind() != reflect.Ptr && svv.Kind() != reflect.Struct {
		err = fmt.Errorf("source参数必须是一个结构体或者结构体指针")
		return
	}

	// 检查 target 是否是结构体指针
	if tvv.Kind() != reflect.Ptr || tvv.Elem().Kind() != reflect.Struct {
		err = fmt.Errorf("target参数数据必须是一个结构体指针")
		return
	}
	tvv = tvv.Elem()
	if svv.Kind() == reflect.Ptr {
		svv = svv.Elem()
	}

	// 存放字段
	fieldItems := make([]reflect.StructField, 0)

	if len(fields) > 0 {
		for _, fieldName := range fields {
			if field, found := svv.Type().FieldByName(fieldName); found {
				fieldItems = append(fieldItems, field)
			}
		}
	} else {
		for i := 0; i < svv.NumField(); i++ {
			fieldItems = append(fieldItems, svv.Type().Field(i))
		}
	}

	for _, field := range fieldItems {
		tV := tvv.FieldByName(field.Name)
		sV := svv.FieldByName(field.Name)
		if tV.IsValid() && sV.IsValid() && tV.Kind() == sV.Kind() {
			tV.Set(sV)
		}
	}
	return

}

func StrToArray(str string) []int64 {
	var (
		strArray []string
		numArray = make([]int64, 0)
	)
	strArray = strings.Split(str, ",")
	for _, item := range strArray {
		newItem, err := strconv.ParseInt(item, 10, 64)
		if err != nil {
			continue
		}
		numArray = append(numArray, newItem)
	}
	return numArray
}
